# tests/test_main.py

from fastapi.testclient import TestClient
from app.main import app
from app.database import Base, engine, SessionLocal
from app import models
import pytest

client = TestClient(app)

# 使用测试数据库
@pytest.fixture(scope="module")
def test_db():
    # 创建测试数据库表
    Base.metadata.create_all(bind=engine)
    db = SessionLocal()
    yield db
    db.close()
    # 删除测试数据库表
    Base.metadata.drop_all(bind=engine)

def test_webhook_unauthorized(test_db):
    response = client.post("/webhook", json={})
    assert response.status_code == 401

def test_webhook_invalid_payload(test_db):
    headers = {
        "X-Gitlab-Token": "your_webhook_secret",
        "X-Gitlab-Event": "Push Hook"
    }
    response = client.post("/webhook", headers=headers, json={})
    assert response.status_code == 400

def test_webhook_valid_payload(test_db):
    headers = {
        "X-Gitlab-Token": "your_webhook_secret",
        "X-Gitlab-Event": "Push Hook"
    }
    payload = {
        "project": {
            "name": "test-repo",
            "namespace": "test-owner"
        },
        "user_username": "test-pusher",
        "ref": "refs/heads/main",
        "before": "oldsha123",
        "after": "newsha456",
        "commits": [
            {
                "id": "commitsha1",
                "message": "Test commit\n\nSigned-off-by: Tester <tester@example.com>",
                "url": "https://gitlab.com/test-owner/test-repo/commit/commitsha1",
                "author": {
                    "name": "Tester"
                }
            },
            {
                "id": "commitsha2",
                "message": "Another test commit",
                "url": "https://gitlab.com/test-owner/test-repo/commit/commitsha2",
                "author": {
                    "name": "Tester"
                }
            }
        ]
    }
    response = client.post("/webhook", headers=headers, json=payload)
    assert response.status_code == 200
    assert response.json() == {"message": "Processed"}

    # 验证数据库中记录
    event = test_db.query(models.WebhookEvent).filter(models.WebhookEvent.repository_name == "test-repo").first()
    assert event is not None
    assert event.pusher == "test-pusher"
    assert len(event.invalid_commits) == 1
    assert event.invalid_commits[0].sha == "commitsha2"
